<!-- 多级联动面版组件 -->
<template>
  <div class="cascade-panel">
    <div class="panel-wrap">
      <div class="item-label">
        {{label}}（{{count}}）
      </div>
      <div class="search">
        <el-button
         type="button"
         icon="el-icon-circle-plus-outline"
         @click="toAdd"
         :disabled="isDisabled">
        </el-button>
        <el-input
          v-model.trim="searchValue"
          clearable
          @clear="clearSearch"
          placeholder="搜索"
          prefix-icon="el-icon-search"
          @input="onSearch"
        ></el-input>
      </div>
      <ul class="panel-item"  v-loading="listLoading" element-loading-text="loading">
        <div class="none" v-if="count==0">暂无数据</div>
        <li
          v-for="items in listData"
          :key="items.id"
          @click="onActivate(items.id)"
          class="list-item"
          :class="{isactivate:items.id==activateId}"
        >
          <div class="item-content">
            <div class="content-header">
              <span>{{items.catalogName || items.categoryName}}</span>
              <span class="operation" v-show="items.id==activateId">
                <i class="el-icon-delete" style="padding:0 10px;" @click.stop="onDelete(items.id)"></i>
                <i class="el-icon-edit" @click.stop="onEdit(items)"></i>
              </span>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  name: 'cascadePanel',
  props: {
    label: { // 列表标题
      type: String,
      default: String
    },
    editUrl: { // edit跳转路由
      type: String,
      default: String
    },
    addUrl: { // add跳转路由
      type: String,
      default: String
    },
    parentId: { // data id
      type: Number,
      default: Number
    },
    level: { // 层级
      type: Number,
      default: Number
    },
    listTotal: { // 总列数
      type: Number,
      default: Number
    },
    clear: { // 是否清空
      type: Boolean,
      default: Boolean
    },
    keep: { // 是否恢复选中
      type: Boolean,
      default: Boolean
    },
    isRelated: { // 是否联动
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      searchValue: '',
      activateId: '',
      listData: [],
      startData: [],
      listLoading: false,
      isDisabled: false
    }
  },
  computed: {
    count () {
      return this.listData ? this.listData.length : 0
    }
  },
  watch: {
    parentId: { // 更新列表
      handler () {
        if (this.isRelated) {
          this.updateList()
        }
      }
    },
    clear: {
      handler (newVal, oldVal) {
        if (newVal && this.isRelated) {
          this.clearData()
        }
      }
    },
    keep: { // 恢复激活状态
      handler (newVal, oldVal) {
        if (newVal) {
          const selectId = sessionStorage.getItem('select' + Number(this.level - 1))
          if (selectId) {
            this.isDisabled = false
            this.getData(selectId)
          }
          this.activateId = sessionStorage.getItem('select' + this.level)
        }
      }
    }
  },
  mounted () {
    if (this.parentId === null) {
      this.isDisabled = true
    } else {
      this.isDisabled = false
    }
    if (this.isRelated) {
      if (this.level === 0) { // 初始化加载第一列
        this.getData(this.parentId)
      }
    } else {
      this.getData(this.parentId)
    }
  },
  methods: {
    getData (parentId) {
      if (Number(parentId) < 0 || parentId === 'null') { return false }
      if (!this.$auth(`${this.$route.meta.permissionCode}:list`)) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      this.listLoading = true
      this.$emit('getListData', parentId, this.level)
    },
    updateList () {
      const parentId = this.parentId !== null ? this.parentId : sessionStorage.getItem('select' + Number(this.level - 1))
      if (parentId !== null) {
        this.isDisabled = false
        this.activateId = ''
        this.getData(parentId)
        sessionStorage.removeItem('select' + this.level)
      } else {
        this.isDisabled = true
      }
    },
    onActivate (id) { // 选中
      this.activateId = id
      if (this.level + 1 < this.listTotal) {
        this.$emit('onChange', id, this.level + 1)
      }
      sessionStorage.setItem('select' + this.level, id)
    },
    clearData () { // 清空
      this.listData = []
      this.startData = []
      this.activateId = ''
      sessionStorage.removeItem('select' + this.level)
      this.$emit('onClear', this.level)
    },
    init () {
      // 清空当前列选中
      this.activateId = ''
      sessionStorage.removeItem('select' + this.level)
      // 清空后代列表
      if (this.isRelated) {
        for (let level = 0; level < this.listTotal; level++) {
          if (level > this.level) {
            this.$emit('onClear', level, true)
          }
        }
      }
    },
    onSearch () {
      // eslint-disable-next-line no-useless-escape
      this.searchValue = this.searchValue.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, '')
      const that = this
      if (!that.searchValue) {
        this.clearSearch()
        return false
      }
      this.listData = this.startData.filter(function (item) {
        const name = item.catalogName || item.categoryName
        return (
          name.toLowerCase().includes(that.searchValue.toLowerCase())
        )
      })
      this.init()
    },
    clearSearch () {
      this.init()
      this.listData = cloneDeep(this.startData)
    },
    toAdd () {
      if (!this.$auth(`${this.$route.meta.permissionCode}:add`)) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      const id = this.level === 0 ? this.parentId : sessionStorage.getItem('select' + Number(this.level - 1))
      this.$router.push({ name: this.addUrl, params: { level: this.level, parentId: id } })
    },
    onDelete (id) {
      if (!this.$auth(`${this.$route.meta.permissionCode}:delete`)) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      this.$confirm('删除后不可恢复，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('deleteItem', id, this.level)
      })
    },
    onEdit (item) {
      if (!this.$auth(`${this.$route.meta.permissionCode}:edit`)) {
        // 权限控制
        this.$alert('您没有权限。')
        return false
      }
      const itemId = item.id
      this.$router.push({ name: this.editUrl, params: { id: itemId, level: this.level, type: this.label, data: item } })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.cascade-panel{
  .panel-wrap{
    position: relative;
    box-shadow: -2px 2px 10px #ccc;
    border-radius: 15px;
    .item-label{
      background: #ddd;
      text-align: center;
      padding: 15px;
      border-radius: 15px 15px 0 0;
    }
    .panel-item{
      height: 600px;
      overflow-y: auto;
      background: #fff;
      .none{
        width: 100%;
        height: 100%;
        line-height: 600px;
        text-align: center;
      }
      li{
        padding: 20px 15px;
      }
      li:hover{
        background: #eee;
        box-shadow: -2px 2px 10px #ccc;
        color: #fe8466;
      }
      .isactivate{
        background: #eee;
        box-shadow: -2px 2px 10px #ccc;
        color: #fe8466;
      }
      .item-content{
        .content-header{
          display: flex;
          justify-content: space-between;
          align-items: center;
          .operation{
            min-width: 52px;
            text-align: right;
          }
        }
      }
    }
    .search{
      display: flex;
      padding: 15px 20px;
      justify-content: space-between;
      align-items: center;
      .el-button{
        background: #f5f5f5;
        color: #fe8466;
        font-size: 20px;
        border: none;
        margin-left: -10px;
      }
    }
  }
}
</style>
